<%@ include file="../import_page.jsp"%>
<%@ page import="java.util.List"%>
<%@ page import="java.io.File"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page
	import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.io.FilenameUtils"%>
<%
	//login checking
	if (!loginedChecking(session, UsersType.staff)) {
		//user don't login
		//redirect to home page
		response.sendRedirect(URL_HOMEPAGE);
		return;
	}

	//select unit check
	if (!selectUnitCheck(session)) {
		//if user didn't select an Unit
		//redirtect to select page
		response.sendRedirect(URL_SELECT_UNIT);
		return;
	}

	Units selectUnit = (Units) session
			.getAttribute(SESSION_SELECT_UNIT);
	String errMsg = null;
	AssignmentCollector ac = null;

	//try to catch Assignment ID input
	String acIdStr = request.getParameter(PAR_ASSIGNMENT_ID);
	AssignmentsControl aCon = new AssignmentsControl();
	try {
		int acId = Integer.parseInt(acIdStr);

		ac = aCon.getAssignment(acId);

		//Check the unit of assignment is match the selected unit
		if (ac.getUnitID().indexOf(selectUnit.getId()) < 0) {
			throw new Exception(
					"Select Unit do not match the Assignment collector Unit");
		}

	} catch (Exception err) {
		aCon.closeDBConnection();
		response.sendRedirect(URL_VIEW_ASSIGNMENT);
		return;
	}

	try {
		//Process upload file & field
		//Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

		//Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		//upload MaximumSize
		upload.setFileSizeMax(MAX_FILE_SIZE); //Maximum File size 4MB 
		upload.setSizeMax(MAX_REQUEST_SIZE); //Maximum Request size 16.001MB (need include the size of request text)

		//find the upload file & start upload process (only process one upload file)
		List listItem = upload.parseRequest(request);
		Iterator liI = listItem.iterator();

		//Hashtable for fill data
		Hashtable<Integer, AssignmentMaterial> amTb = new Hashtable<Integer, AssignmentMaterial>();
		Hashtable<Integer, FileItem> uploadTb = new Hashtable<Integer, FileItem>();
		ArrayList<Integer> reUseOrder = new ArrayList<Integer>();

		while (liI.hasNext()) {
			FileItem aItem = (FileItem) liI.next();
			if (aItem.isFormField()) {
				String name = aItem.getFieldName();
				String value = aItem.getString();
				if (value == null)
					value = "";

				int strBreak = name.indexOf("_");
				if (strBreak < 0)
					continue;

				String type = name.substring(0, strBreak);
				int order = Integer.parseInt(name
						.substring(strBreak + 1));

				AssignmentMaterial am = amTb.get(order);
				if (am == null) {
					am = new AssignmentMaterial(ac.getId(), order, "");
					amTb.put(order, am);
				}

				if (type.equalsIgnoreCase("name")) {
					am.setName(value);
				} else if (type.equalsIgnoreCase("info")) {
					am.setInfo(value);
				} else if (type.equalsIgnoreCase("file")) {
					am.setFileName(value);
				} else if (type.equalsIgnoreCase("order")) {
					int oldOrder = Integer.parseInt(value);
					if (oldOrder > 0)
						reUseOrder.add(oldOrder);
				}
			} else {
				//found the item of upload file
				String fieldName = aItem.getFieldName();
				String fileName = aItem.getName();
				if (fileName == null || fileName.isEmpty()) {
					//empty file upload, skip
					continue;
				}

				int strBreak = fieldName.indexOf("_");
				if (strBreak < 0 || !fieldName.startsWith("file"))
					continue;

				int order = Integer.parseInt(fieldName
						.substring(strBreak + 1));
				uploadTb.put(order, aItem);
			}
		}
		//finish to collector data
		//start to validate
		ArrayList<AssignmentMaterial> listAm = new ArrayList<AssignmentMaterial>();
		listAm.addAll(amTb.values());
		Iterator<AssignmentMaterial> lamI = listAm.iterator();
		while (lamI.hasNext()) {
			AssignmentMaterial am = lamI.next();
			if (am.getOrder() < 1)
				throw new Exception("Incorrect Orders");
			if (am.getName().isEmpty()
					|| am.getName().length() > AssignmentMaterial.NAME_MAX_LENGTH)
				throw new Exception("Incorrect name format");
		}
		//If no old material found, delete all file & record of material by assignment ID
		if (reUseOrder.isEmpty()) {
			aCon.removeAllAm(ac.getId());
		} else {
			//keep the useful file, delete others file & all record
			aCon.removeUselessAmFile(ac.getId(), reUseOrder);
		}
		//Update Assignment Material info
		if (!listAm.isEmpty()) {
			aCon.updateAssignmentMaterial(listAm);

			//start to process uploaded file
			lamI = listAm.iterator();
			while (lamI.hasNext()) {
				int amOrder = lamI.next().getOrder();
				FileItem uploadItem = uploadTb.get(amOrder);
				//not all material have submited file
				if (uploadItem == null)
					continue;

				String fileName = FilenameUtils.getName(uploadItem
						.getName());

				//Create the folder of the assignment if it is not exist
				File fileObj = new File(
						AssignmentsControl.getMaterialPath() + "\\"
								+ ac.getId());
				FileUtils.forceMkdir(fileObj);

				//Write the file
				fileObj = new File(fileObj, fileName);
				//Check the old is exists or not. If exists, delete the older one.
				if (fileObj.exists())
					if (!fileObj.delete())
						throw new Exception(
								"Can't replace the file uploaded before"); //Can't delete the old file

				//write the file to storage
				uploadItem.write(fileObj);

				aCon.updateAmFilename(ac.getId(), amOrder, fileName);
			}
		}
		aCon.closeDBConnection();

	} catch (Exception err) {
		aCon.closeDBConnection();
		errMsg = err.toString();
	}
%>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="../img_style.css" />
</head>
<body>
	<%
		if (!isEmptyString(errMsg)) {
	%>
	<p><%=errMsg%></p>
	<%
		}
		ArrayList<AssignmentMaterial> listAm = aCon
				.getAssignmentMaterial(ac.getId());
	%>
	<table border="1">
		<tr>
			<td>Unit (ID)</td>
			<td><%=selectUnit.getName()%> (<%=selectUnit.getId()%>)</td>
		</tr>
		<tr>
			<td>Assignment Name (ID)</td>
			<td><%=ac.getName()%> (<%=ac.getId()%>)</td>
		</tr>
	</table>
	<hr />
	<table border="1">
		<%
			Iterator<AssignmentMaterial> lamI = listAm.iterator();
			while (lamI.hasNext()) {
				AssignmentMaterial am = lamI.next();
		%>
		<tr>
			<td>Name:</td>
			<td><%=am.getName()%></td>
		</tr>
		<tr>
			<td>Information:</td>
			<td><%=muiliteLineString(am.getInfo())%></td>
		</tr>
		<tr>
			<td>File:</td>
			<td>
				<%
					if (isEmptyString(am.getFileName())) {
				%> <%=IMG_NO%> <%
 	} else {
 			Hashtable<String, String> keys = new Hashtable<String, String>(
 					2);
 			keys.put(PAR_ASSIGNMENT_ID, Integer.toString(ac.getId()));
 			keys.put(PAR_AM_ORDER, Integer.toString(am.getOrder()));
 %> <a href="<%=addParmeterToUrl(URL_DOWNLOAD_MATERIAL, keys)%>"><%=IMG_DOWNLOAD + am.getFileName()%></a>
				<%
					}
				%>
			</td>
		</tr>
		<%
			}
		%>
	</table>
	<p><%=isEmptyString(errMsg) ? "Update complete" : "Update fail"%></p>
</body>
</html>